package com.huiqiao.sys.service.impl;


import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huiqiao.sys.constant.SysConstant;
import com.huiqiao.sys.domain.*;
import com.huiqiao.sys.mapper.RoleMapper;
import com.huiqiao.sys.mapper.RoleUserMapper;
import com.huiqiao.sys.mapper.UserMapper;
import com.huiqiao.sys.service.UserService;
import com.huiqiao.sys.utils.DataGridView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleUserMapper roleUserMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public User login(UserVo userVo) {
        //明⽂
        //⽣成密⽂
        String pwd = DigestUtils.md5DigestAsHex(userVo.getPwd().getBytes());
        userVo.setPwd(pwd);
        return userMapper.login(userVo);

    }

    @Override
    public DataGridView loadAllUser(UserVo userVo) {
        Page<Object> page = PageHelper.startPage(userVo.getPage(), userVo.getLimit());
        Weekend<User> weekend = Weekend.of(User.class);
        WeekendCriteria<User, Object> userObjectWeekendCriteria = weekend.weekendCriteria();
        //用户名称
        if (StrUtil.isNotBlank(userVo.getRealname())){
            userObjectWeekendCriteria.andLike(User::getRealname, "%" + userVo.getRealname() + "%");
        }
        //用户登陆名称
        if (StrUtil.isNotBlank(userVo.getLoginname())){
            userObjectWeekendCriteria.andLike(User::getLoginname, "%" + userVo.getLoginname() + "%");
        }
        //用户地址
        if (StrUtil.isNotBlank(userVo.getAddress())){
            userObjectWeekendCriteria.andLike(User::getAddress, "%" + userVo.getAddress() + "%");
        }
        //用户电话号码
        if (StrUtil.isNotBlank(userVo.getPhone())){
            userObjectWeekendCriteria.andLike(User::getPhone, "%" + userVo.getPhone() + "%");
        }
        //用户身份证
        if (StrUtil.isNotBlank(userVo.getIdentity())){
            userObjectWeekendCriteria.andLike(User::getIdentity, "%" + userVo.getIdentity() + "%");
        }
        //用户性别
        if (Objects.nonNull(userVo.getSex())){
            userObjectWeekendCriteria.andEqualTo(User::getSex, userVo.getSex());
        }
        List<User> data = userMapper.selectByExample(weekend);
        return new DataGridView(page.getTotal(), data);

    }

    //添加
    @Override
    public void addUser(UserVo userVo) {
        //设置默认密码?
        if (userVo.getPwd() == null){
            userVo.setPwd(DigestUtils.md5DigestAsHex(SysConstant.USER_DEFAULT_PWD.getBytes()));
        }
        userMapper.insertSelective(userVo);
    }

    //删除
    @Override
    public void deleteUser(UserVo userVo) {
        userMapper.deleteByPrimaryKey(userVo.getUserid());
    }

    //修改
    @Override
    public void updateUser(UserVo userVo) {
        userMapper.updateByPrimaryKeySelective(userVo);
    }

    //批量删除
    @Override
    public void deleteBatchUser(Integer[] ids) {
//        Arrays.asList(ids).stream().forEach(userMapper::deleteByPrimaryKey);
        Arrays.asList(ids).stream().forEach(id -> userMapper.deleteByPrimaryKey(id));
    }

    //重置密码
    @Override
    public void resetUserPwd(UserVo userVo) {
        try {
            userVo.setPwd(DigestUtils.md5DigestAsHex(SysConstant.USER_DEFAULT_PWD.getBytes()));
            userMapper.updateByPrimaryKeySelective(userVo);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("重置密码失败");
        }
    }

    @Override
    public DataGridView initUserRole(Integer userid) {
        //查询所有可用的角色
        List<Role> roles = roleMapper.select(new Role().setAvailable(SysConstant.AVAILABLE_TRUE));
        //查询当前用户拥有的角色
        List<RoleUser> roleUsers = roleUserMapper.select(new RoleUser().setUid(userid));

        List<Role> roleList = roleUsers.stream().map(RoleUser::getRid)
                .map(roleMapper::selectByPrimaryKey)
                //空指针
                .filter(Objects::nonNull)
                //去重
                .distinct()
                .collect(Collectors.toList());

        ArrayList<Map<String, Object>> data = new ArrayList<>();
        for (Role role : roles) {
            Boolean LAY_CHECKED = false;
            for (Role role1 : roleList) {
                if (role1.getRoleid() == role.getRoleid()){
                    LAY_CHECKED = true;
                }
            }

            Map<String, Object> map = new HashMap<>();
            map.put("roleid", role.getRoleid());
            map.put("rolename", role.getRolename());
            map.put("roledesc", role.getRoledesc());
            map.put("LAY_CHECKED", LAY_CHECKED);
            data.add(map);
        }
        return new DataGridView(data);

        }

    @Override
    public void saveUserRole(UserVo userVo) {
        Integer userid = userVo.getUserid();
        Integer[] ids = userVo.getIds();
        //根据用户id删除sys_role_user里面的数据
        this.roleUserMapper.delete(new RoleUser().setUid(userid));
        //保存角色和用户的关系
        for (Integer id : ids) {
            this.roleUserMapper.insertSelective(new RoleUser().setUid(userid).setRid(id));
        }
    }

}


/*    @Override
    public User login(UserVo userVo) {
        // 明文密码
        String rawPwd = userVo.getPwd();
        // 生成密文
        String encryptedPwd = DigestUtils.md5DigestAsHex(rawPwd.getBytes());

        // 使用tk.mybatis的select方法来查询用户列表
        User condition = new User();
        condition.setLoginname(userVo.getLoginname());
        condition.setPwd(encryptedPwd);
        List<User> users = userMapper.select(condition);

        // 检查查询结果并返回第一个匹配的用户
        if (users != null && !users.isEmpty()) {
            // 用户存在，返回第一个用户信息
            return users.get(0);
        } else {
            // 用户不存在或密码不匹配，返回null
            return null;
        }
    }*/
